package com.personal.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * web请求处理器(记录一些请求的信息)
 */
@Component
@Aspect
@Slf4j
public class WebLogAspect {

    @Pointcut("execution(public * com.personal.controller.*.*..*(..))")
    public void webLog(){

    }

    /**
     * 使用aop的前置通知拦截请求信息
     * @param joinPoint
     * @throws Throwable
     */
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable{
        //接收请求,记录请求内容 记录在数据库中(redis mongdb)
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //记录下请求内容
        String url = request.getRequestURL().toString();
        String method = request.getMethod();
        String ip = request.getRemoteAddr();
        log.info("url:"+url);
        log.info("http method:"+method);
        log.info("ip:"+ip);
        Enumeration<String> enu = request.getParameterNames();
        while(enu.hasMoreElements()){
            String name = enu.nextElement();
            log.info("name:{},value:{}",name,request.getParameter(name));
        }
    }

    /**
     * 后置通知
     * @param ret
     */
    @AfterReturning(returning = "ret",pointcut = "webLog()")
    public void doAfterReturning(Object ret){
        //处理完请求,返回内容
        log.info("response:{}",ret);
    }
}
